#!/usr/bin/env python
# encoding: utf-8
from googletrans import Translator
import argparse
import chardet
import sys
import time
import re

from config import AppConfig
from model import Model

reload(sys)
sys.setdefaultencoding('utf-8')

parser = argparse.ArgumentParser()
parser.add_argument('--title', default='极品狂少', help='书名')
args = parser.parse_args()

title = args.title
filename = title + '.txt'
now = time.time()

print title, filename

# 打开数据库连接
# config = {'host':'localhost', 'user':'root', 'password':'123456', 'database':'wulinstory', 'charset':'utf8'};
model = Model(AppConfig.DATABASE)

# SQL 插入语句
model.add('book', {'title':title, 'addtime':now})

# 获取所有记录列表
results = model.find('book', {'title':title})
book_id = results['id']
print 'book_id', book_id

def fetchChapter(line, title):
    if title=='极品狂少':
        return re.findall(u"第(\d+)章", line)
    elif title=='潮湿':
        return re.findall(u"(\d+)、", line)
    elif title=='崩坏星河':
        return re.findall(u"(第[一二三四五六七八九十百把千零]+[章卷])|(文案)|(后记)", line)
    elif title=='爱上外星少女':
        return re.findall(u"(第[一二三四五六七八九十百把千零]+章)", line)
    elif title=='1855美国大亨':
        return re.findall(u"(第[一二三四五六七八九十百把千零0123456789]+[章])", line)
    elif title=='血族传说':
        return re.findall(u"(第[一二三四五六七八九十百把千零0123456789]+[章]\s+)|(前言)", line)
    elif title in ('重生是精灵','我的老婆亚瑟王','超人类进化'):
        return re.findall(u"(^第[一二三四五六七八九十百把千零〇0123456789]+[章卷])", line)
    elif title in ('异世之风流大法师','道气武','第十元素'):
        return re.findall(u"(第[一二三四五六七八九十百把千零〇\-0123456789]+章)", line)
    elif title in ('绝世轮回'):
        return re.findall(u"(第[1234567890一二三四五六七八九十百把千零]+章)|(^\d+)", line)
    
    else:
        raise Exception(title + " re chapter failed")

translator = Translator()
with open(filename) as file:
    k = 0
    page = 0
    chapter_id = 0
    is_chapter = False
    for line in file:
        #f_charInfo = chardet.detect(line)
        #print f_charInfo, k
        #exit()

        line = line.decode('GBK','ignore').strip()

        if line == '' or len(re.findall(u"^ps(\d+)：", line))>0:
            continue

        # find chapter
        chapter = fetchChapter(line, title)
        #print chapter, line
      
        if len(chapter) > 0:
            #line = line.replace('把', '百')
            #上一次也是chapter则此次略过
            if is_chapter is True:
                print 'Repeat chapter', chapter, page
                continue

            old_chapter = model.find('chapter', {'book_id':book_id, 'name':line})
            if not old_chapter:
                chapter_id = model.add('chapter', {'book_id':book_id, 'page':page, 'name':line})
            else:
                chapter_id = old_chapter['id']
            
            print 'chapter', chapter, 'chapter_id', chapter_id, 'name', line, 'page', page
            page = page+1
            is_chapter = True
        else:
            is_chapter = False

        #continue
        # find old line
        old_content = model.find('content', {'book_id':book_id, 'book_page':k})
        if old_content:
            #print 'book_page', k, ' old_content_id', old_content['id']
            model.save('content', {'id':old_content['id']}, {'chapter_id':chapter_id})

            if len(chapter) > 0:
                en_text = old_content['en_text'].strip('、')
                if en_text.isdigit():
                    en_name = 'Chapter ' + en_text
                else:
                    en_name = old_content['en_text']

                model.save('chapter', {'id':chapter_id}, {'en_name':en_name})

            k = k+1
            continue

        print 'line', k, chapter_id, line
        text = ''
        state = 1
        try:
            line_text = translator.translate(line)
            text = line_text.text
        except Exception as e:
            state = 0
            print 'translateException', e
        
        print 'line', k, chapter_id, text

        model.add('content', \
            {'book_id':book_id, 'book_page':k, 'chapter_id':chapter_id, 'state':state, 'cn_text':line, 'en_text':text})

        if len(chapter) > 0:
            model.save('chapter', {'id':chapter_id}, {'en_name':text})
        
        k = k+1
        #break


